import axios from 'axios';

const baseUrl = 'http://localhost:3001';
// 创建 Axios 实例
const apiClient = axios.create({
    baseURL: baseUrl, // 替换为你的后端地址
    timeout: 10000, // 超时时间 10s
    headers: {
        "Content-Type": "application/json"
    }
});

// 请求拦截器
apiClient.interceptors.request.use(
    async (config) => {
        const token = localStorage.getItem('token'); // 读取 Token
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`; // 设置 Token
        }
        return config;
    },
    (error) => Promise.reject(error)
);

// 响应拦截器
apiClient.interceptors.response.use(
    (response) => {

        return response.data
    },
    async (error) => {

        const originalRequest = error.config;
        if (!originalRequest._retry) {
            originalRequest._retry = 0;
        }
        console.log(error.response)
        // 处理 401 未授权错误，尝试刷新 Token
        if (originalRequest._retry < 3) {
            originalRequest._retry += 1;
            try {
                const newToken = await refreshToken(); // 刷新 Token 方法
                localStorage.setItem('token', newToken);
                apiClient.defaults.headers['Authorization'] = `Bearer ${newToken}`;
                return apiClient(originalRequest); // 重新发送原请求
            } catch (err) {
                console.error('Token 刷新失败', err);
                return Promise.reject(error);
            }
        }

        return Promise.reject(error);
    }
);

// 模拟刷新 Token 方法
async function refreshToken() {
    // 这里可以调用后端的刷新 Token 接口
    var myHeaders = new Headers();

    var raw = JSON.stringify({
        "username": "xuegang",
        "password": "sippr@073111"
    });

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        headers: {
            "Content-Type": "application/json"
        },
        body: raw,
        redirect: 'follow'
    };

    try {
        const response = await fetch(baseUrl + "/user/login", requestOptions);
        const res = await response.json();  // 解析 JSON 数据

        if (res.code === 0) {
            return res.data;  // 返回 token
        } else {
            console.error("Failed to refresh token:", res);
            return null; // 失败时返回 null
        }
    } catch (error) {
        console.error("Error refreshing token:", error);
        return null;
    }
}

// 统一请求方法，支持 GET、POST、DELETE
const request = async (method, url, data = null, retries = 3) => {
    try {
        const config = { method, url };
        if (method === 'GET') {
            config.params = data;
        } else {
            config.data = data;
        }
        return await apiClient(config);
    } catch (error) {
        if (retries > 0 && !error.response) {
            console.warn(`请求失败，正在重试... 剩余 ${retries} 次`);
            return request(method, url, data, retries - 1); // 递归重试
        }
        return Promise.reject(error);
    }
};
// 封装 GET 请求
export const get = (url, params) => request('GET', url, params);

// 封装 POST 请求
export const post = (url, data) => request('POST', url, data);

// 封装 DELETE 请求
export const del = (url, params) => request('DELETE', url, params);